import { defineStore } from 'pinia'
import { ref } from 'vue'
import { TokenService } from '@/utils/token'
import { Api } from '@/api'
import type { UserInfo } from '@/api'

export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref<string | null>(TokenService.getToken())
    const userInfo = ref<UserInfo | null>(null)
    const isLoggedIn = ref(!!token.value)

    // 登录
    async function login(username: string, password: string) {
      const res = await Api.login({ username, password })
      token.value = res.data.token
      TokenService.setToken(res.data.token)
      if (res.data.refreshToken) {
        TokenService.setRefreshToken(res.data.refreshToken)
      }
      isLoggedIn.value = true
      await getUserInfo()
    }

    // 获取用户信息
    async function getUserInfo() {
      if (!token.value) return
      const res = await Api.getUserInfo()
      userInfo.value = res.data
    }

    // 退出登录
    async function logout() {
      try {
        // 即使接口调用失败，也要清除本地状态
        await Api.logout().catch((error) => {
          console.error('Logout API failed:', error)
        })
      } finally {
        // 清除所有状态
        token.value = null
        userInfo.value = null
        isLoggedIn.value = false
        TokenService.clear()
        // 清除其他需要重置的状态
        localStorage.removeItem('lastRoute')
        sessionStorage.clear()
      }
    }

    return {
      token,
      userInfo,
      isLoggedIn,
      login,
      getUserInfo,
      logout,
    }
  },
  {
    persist: true,
  },
)
